import {defineStore} from 'pinia';
import {getToken, removeToken, setToken} from '../utils/token-utils';
import {reqLogin, reqLogout, reqUserInfo} from '@/api/userInfo';
import type {infoParamsType, userInfoType, resLoginType} from '@/api/userInfo';
import type {RouteRecordRaw} from 'vue-router';
import {staticRoutes} from '@/router/routes';


/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
//设定userInfo小仓库的类
export interface userInfoState {
  token: string,
  userInfo: userInfoType,
  menuRoutes: RouteRecordRaw[]
}

export const useUserInfoStore = defineStore('userInfo', {

  state: (): userInfoState => ({
    token: (getToken() as string) || '',
    //更据类型修改基础状态
    userInfo: {
      routes: [],
      buttons: [],
      roles: [],
      name: '',
      avatar: '',
    },
    menuRoutes: staticRoutes,
  }),

  actions: {
    //设置登入请求
    async login(loginParam: infoParamsType) {
      try {
        //发送请求
        const re = await reqLogin(loginParam);
        //给pinia的token赋值
        this.token = re.token;
        //实现token数据本地化保存
        setToken(this.token);
      } catch (e) {
        return Promise.reject(e);
      }
    },
    //设置获取用户信息的请求
    async getInfo() {
      try {
        //发送请求
        const re = await reqUserInfo();
        //给状态中的Userinfo赋值
        this.userInfo = re;
      } catch (e) {
        return Promise.reject(e);
      }
    },
    //  设置登出请求
    async getLogout() {
      try {
        //不需要登出的返回值，直接发送请求
        await reqLogout();
        this.reset()
      } catch (e) {
        return Promise.reject(e);
      }
    },
    reset(){
      //  移除本地的token
      removeToken()
      //  重置状态
      this.token = '';
      this.userInfo = {
        routes: [],
        buttons: [],
        roles: [],
        name: '',
        avatar: '',
      };
    }
  },
});
